<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>烟花</title>
    <style media="screen">
        * {
            margin: 0;
            padding: 0;
        }

        #box {
            width: 800px;
            height: 600px;
            position: relative;
            margin: 100px auto;
            background: #000000;
            border: 2px solid red;
            overflow: hidden;
        }

        .ball {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            position: absolute;
            bottom: 0;
        }
    </style>
</head>

<body>
    <div id="box"></div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="../js/public.js"></script>
<script>
    function Fireworks(el) {
        this.ele = document.querySelector(el);
        this.bindEvent();
    }

    Fireworks.prototype.bindEvent = function () {
        let that = this;
        this.ele.onclick = function (e) {
            e = e || window.event;
            let fire = that.show();
            fire.style.left = e.offsetX + 'px';
            $(fire).animate({
                top: e.offsetY
            }, 1000, function () {
                fire.remove();
                that.boom(e.offsetX, e.offsetY);
            })
        }
    }

    Fireworks.prototype.show = function () {
        let div = document.createElement('div');
        div.style.backgroundColor = ranColor();
        div.className = 'ball';
        this.ele.appendChild(div);
        return div;
    }

    Fireworks.prototype.boom = function (x, y) {
        let deg = 0;
        let r = 100;
        for (let i = 0; i < 20; i++) {
            let fire = this.show();
            fire.style.left = x + 'px';
            fire.style.top = y + 'px';
            deg += 18;

            let targetX = Math.round(Math.cos(Math.PI / 180 * deg) * r);
            let targetY = Math.round(Math.sin(Math.PI / 180 * deg) * r);

            $(fire).animate({
                left: targetX + x,
                top: targetY + y
            }, function () {
                // this.remove();
                fire.remove();
            })
        }
    }

    Fireworks.prototype.autoFire = function () {
        let that = this;
        setInterval(function () {
            that.ele.onclick({
                offsetX: Math.round(Math.random() * that.ele.offsetWidth),
                offsetY: Math.round(Math.random() * that.ele.offsetHeight)
            })
        }, 2000)
    }

    let a = new Fireworks('#box');
</script>

</html>